/**
 * author: Hanflyee  flyee1980@163.com
 * vision: v1.0
 * data: 2009-7-9
 */
package com.flyee.io.socket{
	
	import com.flyee.io.Config;
	import com.flyee.io.socket.command.down.CommandDown;
	import com.flyee.io.socket.command.up.CommandUp;
	import com.flyee.utils.MyLog;
	
	import flash.errors.EOFError;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.ObjectEncoding;
	import flash.net.Socket;
	
	/**
	 * Socket方式与服务器通讯类
     * 基于AMF3纯对象传输的模式
	 */
	public class SocketConnectionAmf3{
		
		private static var instance : SocketConnectionAmf3;
		
		private var socket : Socket;

		/**
		 * 构造方法,建立连接.绑定事件
		 * params : 内部类的对象，仅此处可用
		 */
		public function SocketConnectionAmf3(){
			socket = new Socket();
			socket.objectEncoding = ObjectEncoding.AMF3;
			socket.connect(Config.getInstance().SOCKET_SERVER, Config.getInstance().SOCKET_PORT);
			
			//绑定SOCKET事件
			socket.addEventListener(Event.CLOSE, closeHandle);
	        socket.addEventListener(Event.CONNECT, connectHandle);
	        socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandle);
	        socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandle);
	        socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandle);

		}
		
		/**
		 * 取得该类的单例
		 */
		public static function getInstance() : SocketConnectionAmf3 {
			if(instance==null)
				instance = new SocketConnectionAmf3();
			return instance;
		}
		
		public function closeHandle(event : Event) : void {
			MyLog.debug("socket is closed");
		}
		
		public function connectHandle(event : Event) : void {
			MyLog.debug("socket connect success");
		}
		
		public function ioErrorHandle(event : IOErrorEvent) : void {
			MyLog.debug("socket io error");
		}
		
		public function securityErrorHandle(event : SecurityErrorEvent) : void {
			MyLog.debug("socket has security error");
		}
		
		/**接收下行对象并执行回调方法*/
		public function socketDataHandle(event : ProgressEvent) : void {
			MyLog.debug("socket receive data");
			try{
				var cmd:CommandDown = socket.readObject();
		    	HandlerDispatcher.dispatch(cmd);
			}catch(eof:EOFError){
				MyLog.error("socket read eoferror!!!!"+eof.message);
			}catch(ioe:IOError){
				MyLog.error("socket read io error!!!!"+ioe.message);
			}
		}

		/**发送上行指令*/
		public function sendRequest(command : CommandUp) : void {
			if(command.handler==null)
			{
				MyLog.error("handler is need for command");
				throw new Error("handler is need for command");
			}
			try{
				socket.writeObject(command);
				socket.flush();
			}catch(error:IOError){
				MyLog.error("socket write io error!!!!"+error.message);
			}
		}
	}
		
}